Skip to main content

Arrays

πŸ“Œ What is an Array?​

An array is a collection of elements of the same data type, stored in contiguous memory locations.

In simple Array in Java is a data structure that allows you to store multiple values of the same data type in a single variable, instead of declaring separate variables for each value.

Example:​

Instead of:

int mark1 = 90;
int mark2 = 85;
int mark3 = 76;

You can write:

int[] marks = {90, 85, 76};

βœ… Key Points​

  • Arrays in Java are objects.
  • Arrays can be of primitive types or objects.
  • The size is fixed once declared.

πŸ”’ Array Declaration & Initialization​

Syntax:​

datatype[] arrayName;       // Preferred
datatype arrayName[]; // Legal but not preferred

Initialization:​

int[] numbers = new int[5]; // Declares array of size 5 with default values (0)

Declaration + Initialization:​

int[] marks = {90, 85, 76, 92, 88}; // Static initialization

πŸ—οΈ Memory Representation​

Arrays are stored in contiguous memory locations, which allows efficient indexed access.

Index:   0     1     2     3     4
Data : 90 85 76 92 88

πŸ”Ž Array Object in Java​

When you create an array, Java internally does:

int[] arr = new int[5];

Java creates an object of type int[] with default values set to 0.


🧠 Default Values​

Data TypeDefault Value
int0
double0.0
booleanfalse
Objectnull

πŸ“š Characteristics of Arrays in Java​

  1. Fixed Size: Once created, its size cannot be changed.
  2. Homogeneous Elements: All elements must be of the same type.
  3. Indexed Access: First index is 0, last index is (length - 1).
  4. Stored in Heap Memory: Arrays are objects in Java and allocated in heap.

🎯 Why Use Arrays?​

  • Efficient Data Management: Store multiple elements without multiple variables.
  • Indexed Access: Quickly access any element using its index.
  • Improves Code Readability and Maintenance

πŸ” Accessing & Modifying Elements​

int[] arr = {10, 20, 30};
System.out.println(arr[1]); // Output: 20
arr[1] = 25;

πŸ”„ Looping through Arrays​

For loop:​

for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}

Enhanced For loop (for-each):​

for (int num : arr) {
System.out.println(num);
}

πŸ“ Array Length​

int len = arr.length; // No parenthesis (it's a field, not method)

🧾 Types of Arrays​

1. Single Dimensional Array​

A simple linear structure:

int[] arr = {1, 2, 3};

2. Multi-Dimensional Array​

Used to represent tables, matrices:

int[][] matrix = new int[3][3];
matrix[0][1] = 5;

Initialization Example:​

int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};

🧩 Jagged Arrays​

An array of arrays where inner arrays can have different lengths.

int[][] jagged = new int[2][];
jagged[0] = new int[3]; // Row 0 has 3 columns
jagged[1] = new int[2]; // Row 1 has 2 columns

βš™οΈ Common Operations​

Finding Maximum Element:​

int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}

Sum of Array:​

int sum = 0;
for (int n : arr)
sum += n;

🧰 Utility Methods from java.util.Arrays​

import java.util.Arrays;

Sorting:​

Arrays.sort(arr);

Printing:​

System.out.println(Arrays.toString(arr));

Comparing Arrays:​

boolean isEqual = Arrays.equals(arr1, arr2);

Copying Arrays:​

int[] copy = Arrays.copyOf(original, newLength);

❗ ArrayIndexOutOfBoundsException​

Occurs when accessing an index outside the range 0 to array.length - 1.

int[] arr = new int[3];
System.out.println(arr[5]); // Throws exception

πŸ“Œ Pros & Cons​

βœ… Advantages:​

  • Fast access via index
  • Simple to use
  • Efficient in memory for fixed-size data

❌ Limitations:​

  • Arrays are Fixed in size , once created it can;t be modified.
  • No built-in dynamic resizing
  • Arrays expect contiguos memory location in the memory for creation. It can;t make ise of disperse memory location.
  • Can store only homogeneous type of data , can’t mix of data types

πŸ†š Array vs ArrayList (Quick Comparison)​

FeatureArrayArrayList
SizeFixedDynamic
Type SupportPrimitives/ObjectsObjects only
PerformanceFaster (less overhead)Slower (more overhead)
UtilitiesBasicRich (add/remove/search)
SyntaxNativeUses methods
MethodsFewRich API Support

πŸ“˜ Best Practices​

  • Use enhanced for-loop when no index is needed.
  • Validate index access to avoid exceptions.
  • Prefer ArrayList if dynamic resizing is needed.

πŸ§ͺ Sample Program​

import java.util.Arrays;

public class ArrayExample {
public static void main(String[] args) {
int[] nums = {5, 3, 7, 1};
Arrays.sort(nums);

for (int n : nums) {
System.out.println(n);
}

System.out.println("Max: " + nums[nums.length - 1]);
}
}

πŸ§ͺ Internal Working​

  • Java arrays are internally represented as zero-based indexed objects.
  • The length is stored as arr.length.
  • Java runtime checks every access for bounds (ArrayIndexOutOfBoundsException).

πŸ’‘ When to Use Arrays​

  • When you know the number of elements in advance.
  • When memory optimization is crucial.
  • When you need fast access via index.

If you need dynamic size, prefer ArrayList.


βœ… Summary​

  • Arrays are essential building blocks for storing multiple items.
  • Java treats arrays as objects.
  • They offer fast access but have size limitations.
  • Understanding arrays builds foundation for mastering collections, data structures, and algorithms.